from django.contrib import auth as django_auth
from django.db.models import Q
from rest_framework import exceptions
from rest_framework import generics
from rest_framework import permissions
from rest_framework import response
from rest_framework import views
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
import requests
from weixin import WXAPPAPI
from weixin.lib.wxcrypt import WXBizDataCrypt
import random
import datetime
import os
import rest_framework as drf

from book import models as models_book
from account import models as models_account
from . import serializers
from souti import settings

from utils import choices
import json
def modify_media_path(media_file):
    return  media_file.replace('/media', '')

class Test(views.APIView):

    def get(self, request):
        return response.Response("hello")


class Account(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)
    def post(self, request):

        university=request.data.get('university')
        phone=request.data.get('phone')

        acc=request.user.account
        if university:
            acc.university=university
        if phone:
            acc.phone=phone
        acc.save()
        data=serializers.AccountSerializer(acc).data
        return response.Response(data)

class OnLogin(views.APIView):

    def post(self,request):
        code = request.data.get('code')
        encrypted_data = request.data.get('encryptedData')
        iv = request.data.get('iv')

        print("code = "+ str(code))
        print("encrypted_data = " + str(encrypted_data))
        print("iv = " + str(iv))
        #获取session_info
        api = WXAPPAPI(appid=settings.APP_ID,
                       app_secret=settings.APP_SECRET)
        session_info = api.exchange_code_for_session_key(code=code)

        #解密userinfo
        session_key = session_info.get('session_key')
        crypt = WXBizDataCrypt(settings.APP_ID, session_key)
        user_info = crypt.decrypt(encrypted_data, iv)

        print("user_info = " + str(user_info))
        #生成用户
        username = user_info['openId']
        password=''
        for i in range(16):
            password += str(random.randint(0,9))
        try:
            account = models_account.Account.objects.get(username=username)
            account.user.set_password(password)
            account.user.save()
        except:
            try:
                user = User.objects.get(username=username)
            except:
                user = User.objects.create_user(
                    username=username,
                    password=password
                )

            # Account
            try:
                print('create account')
                account = models_account.Account.objects.create(
                    user=user,
                    username=username,
                    nickname=user_info['nickName'],
                    country=user_info['country'],
                    city=user_info['city'],
                    language=user_info['language'],
                    province=user_info['province'],
                    gender=str(user_info['gender']),
                    avatarUrl=user_info['avatarUrl'],
                )

            except:
                print('create account failed')
                raise drf.serializers.ValidationError('account create failed! ')

        # Token
        try:
            token = Token.objects.get(user= account.user).delete()
        except:
            pass
        finally:
            token = Token.objects.create(user = account.user)

        #account = user.account
        account.last_login = datetime.datetime.now()
        account.save()

        log_data = models_account.Logdata.objects.create(
            account_id=account.id,
            action_type='0',
        )

        print("token = " + str(token.key))
        data=serializers.AccountSerializer(account).data
        data['token']=token.key
        return response.Response(data)



class MyBooksView(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self,request):
        account = request.user.account

        account_book_list = models_account.AccountBook.objects.filter(account_id = account.id,
                                                                 status = '0')
        book_list = []
        for item in account_book_list:
            try:
                book = models_book.Book.objects.get(id = item.book_id)
                book_list.append(book)
            except:
                continue

        data = serializers.MyBookSerializer(book_list, many=True).data
        for item in data:
            item['cover']=modify_media_path(item['cover'])


        return response.Response(data)


class ChangeMyBook(views.APIView): #类名可能需要稍微修改一下
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        account = request.user.account
        book_ids = json.loads( request.data.get('book_ids') )
        #book_ids=request.POST.getlist('book_ids[]')
        status_eum = ['0', '1']
        status = request.data.get('status')

        print('request.data',request.data)

        print('book_ids=', book_ids)
        print('status=', status)

        if not status in status_eum:
            raise drf.serializers.ValidationError({"detail": "无效的status"})

        if len(book_ids)==0  :
            raise drf.serializers.ValidationError({"detail": "无效的book_id"})

        for book_id in book_ids:
            print('book_id=', book_id)
            try:
                account_book = models_account.AccountBook.objects.get(account_id = account.id,
                                                                     book_id = book_id)
                account_book.status = status
                print('status=', status)
                account_book.save()

            except:
                data = models_account.AccountBook.objects.create(
                    account_id = account.id,
                    book_id = book_id,
                    status = '0',
                )

        return response.Response({"detail": "修改书架成功！"})

class GiveAdvice(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):
        account = request.user.account
        # if not account.university:
        #     raise drf.serializers.ValidationError({"detail": "用户大学信息缺失！"})

        book_id = request.data.get('book_id')
        ti_id=request.data.get('ti_id')
        content=request.data.get('content')
        advice_type=request.data.get('advice_type')

        #####for security
        if book_id and advice_type!='0':
            raise drf.serializers.ValidationError({"detail": "建议类型错误"})
        if ti_id and advice_type!='1':
            raise drf.serializers.ValidationError({"detail": "建议类型错误"})

        if book_id:
            try :
                models_book.Book.objects.get(id=book_id)
            except:
                raise drf.serializers.ValidationError({"detail": "该书不存在！"})
        if ti_id:
            try :
                models_book.Ti.objects.get(id=ti_id)
            except:
                raise drf.serializers.ValidationError({"detail": "该题不存在！"})

        print('book_id=',book_id)

        advice=models_account.Advice.objects.create(
            account=account,
            book_id=book_id,
            ti_id=ti_id,
            content=content,
            advice_type=advice_type,
        )

        return response.Response({"detail": "建议提交成功！"})






